from rest_framework import serializers

from goods.models import SKU


class CartSerializer(serializers.Serializer):
    """
    用户购物车序列化器
    """
    sku_id = serializers.IntegerField(label='商品id', required=True, min_value=1)
    count = serializers.IntegerField(label='商品数据', required=True, min_value=1, )
    selected = serializers.BooleanField(label='是否选中', required=False, default=True)

    def validate(self, attrs):
        #  判断商品是否存在
        #  获取传递的商品id
        sku_id = attrs['sku_id']
        try:
            #  用数据库获取商品
            sku = SKU.objects.get(pk=sku_id)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')
        # 判断商品库存是否充足
        #  获取传递的商品的数量
        count = attrs['count']
        if count > sku.stock:
            raise serializers.ValidationError('库存不足')

        return attrs


class CartSKUSerializer(serializers.ModelSerializer):
    """
    用户购物车列表展示
    """
    count = serializers.IntegerField(label='商品选中的数量')
    selected = serializers.BooleanField(label='商品是否选中')

    class Meta:
        model = SKU
        fields = ['id', 'count', 'name', 'default_image_url', 'price', 'selected']


class CartDeleteSerializer(serializers.Serializer):
    """
    删除购物车信息
    """
    sku_id = serializers.IntegerField(label='商品id', min_value=1)

    def validate(self, attrs):
        #  判断商品是否存在
        #  获取传递的商品id
        sku_id = attrs['sku_id']
        try:
            #  用数据库获取商品
            sku = SKU.objects.get(pk=sku_id)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')

        return attrs
